package com.wiloon.androidx;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.URLSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

import com.wiloon.androidx.entity.Foo;
import com.wiloon.androidx.service.LocalService;
import com.wiloon.androidx.utils.AgentUtils;
import com.wiloon.androidx.utils.CommonUtils;

import org.apache.log4j.Logger;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class FooActivity extends BaseActivity {
    Logger logger = Logger.getLogger(FooActivity.class);

    private LocalService localService;
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            logger.debug("onServiceDisconnected");
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            logger.debug("onServiceConnected");
            localService = ((LocalService.LocalBinder) service).getService();

            if (localService == null) {
                logger.debug("localService is null");
            } else {
                logger.debug("service tag=" + localService.getTag());
            }
        }
    };
    private FooService fooService;
    private TextView txtMonth;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        logger.debug("on created.");
        setContentView(R.layout.foo_activity);
        bindLocalService();

        Button buttonTobar = (Button) findViewById(R.id.button_to_bar);
        buttonTobar.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
                logger.debug("on 'to bar' clicked.");
                unbindLocalService();
                Intent intent = new Intent();
                intent.putExtra("name", "foo");
                intent.setClass(FooActivity.this, BarActivity.class);
                FooActivity.this.startActivity(intent);
                FooActivity.this.finish();
            }
        });
        fooService = new FooServiceImpl(getDatabaseHelper());
        Foo foo = new Foo();
        foo.setId(1l);
        foo.setName("foo name");
        fooService.saveFoo(foo);
        txtMonth = (TextView) findViewById(R.id.monthText);
        // txtMonth.setText("12");
        //txtMonth.setOnClickListener(new OnTxtMonthClickListener());
        SpannableString sp = new SpannableString("abcdeasdfasdfaaaaaaaaaaaaaaaaaaaaaaaaaa");
        sp.setSpan(new URLSpan(urlWrapper("http://www.baidu.com")), 3,
                6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        sp.setSpan(new URLSpan(urlWrapper("http://www.google.com")), 9,
                15, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        txtMonth.append(sp);
        txtMonth.setMovementMethod(LinkMovementMethod
                .getInstance());
    }

    private String urlWrapper(String url) {
        if (!url.startsWith("http://")) {
            return "http://" + url;
        } else {
            return url;
        }
    }

    private void bindLocalService() {
        logger.debug("bindService");
        Intent intent = new Intent(FooActivity.this, LocalService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }

    private void unbindLocalService() {
        logger.debug("unbindService");
        Intent intent = new Intent(FooActivity.this, LocalService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
        unbindService(conn);
    }

    @SuppressLint("SimpleDateFormat")
    private void showDataPickerDialog_Month(String month) {

        View datePickView = View.inflate(this, R.layout.select_month_dialog, null);
        final DatePicker datePicker = (DatePicker) datePickView.findViewById(R.id.month_date_picker);
        ((ViewGroup) ((ViewGroup) datePicker.getChildAt(0)).getChildAt(0)).getChildAt(2).setVisibility(View.GONE);
        Calendar cal = Calendar.getInstance();

        // 参数不为空，设置控件为参数日期，否则设置当前时间
        if (!CommonUtils.isBlank(month)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            try {
                Date date = sdf.parse(month);
                cal.setTime(date);
            } catch (ParseException e) {
                cal.setTimeInMillis(System.currentTimeMillis());
            }
        } else {
            cal.setTimeInMillis(System.currentTimeMillis());
        }

        datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null);

        // 设置控件的最大最小时间
        Calendar cal1 = Calendar.getInstance();
        cal1.set(cal.get(Calendar.YEAR) - 3, Calendar.DECEMBER, 31);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTimeInMillis(System.currentTimeMillis());
        datePicker.setMaxDate(cal2.getTimeInMillis());
        datePicker.setMinDate(cal1.getTimeInMillis());
        // 设置控件不可输入编辑
        AgentUtils.setDisabledEditTexts(datePicker);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(datePickView);

        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                StringBuffer sb = new StringBuffer();

                sb.append(String.format("%d-%02d", datePicker.getYear(), datePicker.getMonth() + 1));
                txtMonth.setText(sb);

                dialog.cancel();
            }
        });

        Dialog dialog = builder.create();
        dialog.show();
    }

    private class OnTxtMonthClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            String month = txtMonth.getText().toString();
            showDataPickerDialog_Month(month);
        }
    }
}
